﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

/**
 * 创建时间：2014/9/22 15:55:11
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace SurfaceAd.Assistant
{
    internal class UserAgentHelper
    {
        public static string UserAgent { get; private set; }
        private const string htmlUserAgent = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN\"">
            <html>
                <head>
                    <script language=""JavaScript"" type=""text/JavaScript"">
                        function printUA()
                        {
                            return navigator.userAgent;
                        }
                    </script>
                </head>
                <body>
                </body>
            </html>";

        public static void GetUserAgentFromWebView(Grid element)
        {
            if (element == null)
            {
                UserAgent = string.Empty;
                return;
            }

            if (!string.IsNullOrWhiteSpace(UserAgent))
            {
                return;
            }

            WebView webView = new WebView();
            webView.Visibility = Visibility.Collapsed;
            webView.NavigateToString(htmlUserAgent);
            ((ICollection<UIElement>)element.Children).Add(webView);
            webView.NavigationCompleted += async delegate(WebView sender, WebViewNavigationCompletedEventArgs args)
            {
                UserAgent = await webView.InvokeScriptAsync("eval", new List<string> { "printUA()" });
                ((ICollection<UIElement>)element.Children).Remove(webView);
            };
        }
    }
}
